﻿using System.Collections.Generic;
using Project_Maverick.Controller.Input;
using Project_Maverick.Screen.GameScreen.Play.Map;
using Project_Maverick.Screen.Playscreen.Character;
using Transformable_Engine_v2.Engine.GameObjects.Containers;

namespace Project_Maverick.Controller
{
    public class Controller : Container
    {
        public BaseMap[] Maps { get; set; }
        public Map.MapNames MapName { get; set; }
        private readonly Dictionary<int, Character> _characters; 
        private int _localCharacterIndex;
        public bool GameStarted { get; private set; }

        public Controller()
        {
            GameStarted = false;
            _characters = new Dictionary<int, Character>();
        }

        public void AddPlayer(int id, Character character, PlayerInputCommand.SourceType source)
        {
            _characters.Add(id, character);
            if (source == PlayerInputCommand.SourceType.Local)
                _localCharacterIndex = id;
        }


        public void StartGame(int timeBeforeStart)
        {
            foreach (BaseMap map in Maps)
            {
                map.GameController = this;
            }
            AddChildren(Maps);

            foreach (KeyValuePair<int, Character> character in _characters)
            {
                var spawnPoint = Map.LoadSpawnPoints(MapName, character.Value.Team.Id)[character.Value.Id];
                character.Value.SetMap(Maps[spawnPoint.MapIndex], spawnPoint.SpawnPosition, spawnPoint.Direction);
                Maps[spawnPoint.MapIndex].AddPlayer(character.Value);
            }

            CallMethod(timeBeforeStart, StartGame);
        }

        void StartGame()
        {
            GameStarted = true;
        }

        public void ReceiveLocalInputPressed(PlayerInputCommand playerInputCommand)
        {
            _characters[_localCharacterIndex].InputPressed(playerInputCommand);
        }

        public void ReceiveLocalInputReleased(PlayerInputCommand playerInputCommand)
        {
            _characters[_localCharacterIndex].InputReleased(playerInputCommand);
        }
    }
}